package jwebtester.dal.utils;

import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

import org.hibernate.cfg.reveng.DefaultReverseEngineeringStrategy;
import org.hibernate.cfg.reveng.TableIdentifier;

/**
 * Represents data entities generation strategy for jwebtester.dal.entities
 * package
 * 
 * @author tillias
 * 
 */
public class HibernateRevengStrategy extends DefaultReverseEngineeringStrategy {

	private static final String ENTITY_PREFIX = "Entity";
	private static final Set<String> LIQUIBASE_TABLES = new HashSet<String>();
	private static final Set<String> SINGULARIZE_TABLES = new HashSet<String>();
	private static final Locale LOCALE = new Locale("en", "US");

	static {
		LIQUIBASE_TABLES.add("DATABASECHANGELOG");
		LIQUIBASE_TABLES.add("DATABASECHANGELOGLOCK");

		SINGULARIZE_TABLES.add("USERS");
		SINGULARIZE_TABLES.add("ROLES");
	}

	public HibernateRevengStrategy() {
		super();
	}

	@Override
	public String tableToClassName(TableIdentifier tableIdentifier) {
		String entityName = super.tableToClassName(tableIdentifier);

		if (SINGULARIZE_TABLES.contains(tableIdentifier.getName().toUpperCase(LOCALE))) {
			entityName = removeLastChar(entityName);
		}

		return entityName + ENTITY_PREFIX;
	}

	@Override
	public boolean excludeTable(TableIdentifier ti) {
		boolean result = super.excludeTable(ti);

		if (LIQUIBASE_TABLES.contains(ti.getName().toUpperCase(LOCALE))) {
			result = true;
		}

		return result;
	}

	public String removeLastChar(String s) {
		if (s == null || s.length() == 0) {
			return s;
		}
		return s.substring(0, s.length() - 1);
	}
}
